package com.ucpaas.paas.web.common.aop;


import com.ucpaas.paas.common.utils.JsonUtils;
import com.ucpaas.paas.common.utils.UserParamsHolder;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 */
@Component
@Aspect
public class UserParamAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * @param pjp
     * @return
     * @throws Throwable
     * @Title：doAround
     * @Description: 环绕触发
     */
    @Around("execution(* *..controller..*.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        logger.debug("UserParamAspect.doAround Params start");
        UserParamsHolder.resetParams();


        Object result = null;
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            HttpSession session = request.getSession();
//             从session中获取用户信息
//            UserSession user = (UserSession) session.getAttribute(SessionEnum.SESSION_USER.toString());
//            if (user != null) {
//                Long userId = user.getUid();
//                UserParams params = new UserParams();
//                params.setUserId(userId);
//                UserParamsHolder.setUserParams(params);
//            }
            logger.info("UserParamAspect.doAround Params->input=>{}", JsonUtils.toJson(UserParamsHolder.getUserParams()));
        } catch (Exception e) {
            logger.error("UserParamAspect.doAround Params组件异常", e);
        }
        try {
            result = pjp.proceed();
        } finally {
            UserParamsHolder.resetParams();
            logger.debug("UserParamAspect.doAround Params end");
        }
        return result;
    }


}
